import copy
import os
import time
import torchvision.transforms as T
import torchvision
import cv2

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
model.eval()

COCO_INSTANCE_CATEGORY_NAMES = [
    '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
    'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
    'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
    'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
    'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
    'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
    'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
    'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
    'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
    'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
    'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
    'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]

from functools import wraps


def fn_timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = function(*args, **kwargs)
        t1 = time.time()
        print("Total time running %s: %.2f seconds" %
              (function.__name__, t1 - t0)
              )
        return result

    return function_timer


@fn_timer
def get_prediction(img, threshold):
    transform = T.Compose([T.ToTensor()])
    img = transform(img)
    pred = model([img])
    pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())]
    pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred[0]['boxes'].detach().numpy())]
    pred_score = list(pred[0]['scores'].detach().numpy())
    pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]
    pred_boxes = pred_boxes[:pred_t + 1]
    pred_class = pred_class[:pred_t + 1]
    return pred_boxes, pred_class


@fn_timer
def object_detection_api(img, threshold=0.5, rect_th=2, text_size=0.75, text_th=1):
    boxes, pred_cls = get_prediction(copy.deepcopy(img), threshold)
    # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    box_pos = []
    for i in range(len(boxes)):
        t = []
        for j in boxes[i]:
            t.append([int(k) for k in j])
        cv2.rectangle(img, t[0], t[1], color=(0, 255, 0), thickness=rect_th)
        box_pos.append(t)
        cv2.putText(img, pred_cls[i], box_pos[i][0], cv2.FONT_HERSHEY_SIMPLEX, text_size, (0, 255, 0),
                    thickness=text_th)
    return img


def getFiles(path):
    ans = []
    for root, dirs, files in os.walk(path):
        for i in files:
            ans.append(root + '/' + i)
    return ans


if __name__ == '__main__':
    if not os.path.exists('annotated_pictures'):
        os.mkdir('annotated_pictures')
    files = getFiles('imgs')
    # img_path = "imgs/IMG_20220920_175144.jpg"
    for i, img_path in enumerate(files):
        cv2.waitKey(1)
        img = cv2.imread(img_path)
        img = object_detection_api(img)
        cv2.imshow('img', img)
        cv2.imwrite('annotated_pictures/{}.jpg'.format(i), img)
